import axios, { AxiosInstance } from "axios";

// --- Axios 实例配置 ---

const API_BASE_URL_SERVER = process.env.NEXT_PUBLIC_API_URL || "http://0.0.0.0:3888";

const createAxiosInstance = (): AxiosInstance => {
  const baseURL = API_BASE_URL_SERVER;
  const instance = axios.create({
    baseURL,
    withCredentials: true, // 关键：允许跨域请求携带Cookie
    headers: {
      "Content-Type": "application/json",
    },
  });

  // 响应拦截器
  instance.interceptors.response.use(
    // 对成功的响应，直接返回data部分
    response => response.data,
    // 对错误的响应进行处理
    error => {
      if (error.response) {
        const { status, data, config } = error.response;
        // 如果是 admin 接口返回401，则跳转到登录页
        if (status === 401 && config.url?.startsWith("/api/admin")) {
          if (typeof window !== "undefined") {
            window.location.href = "/admin";
          }
        }
        // 返回后端提供的错误信息
        return Promise.reject(data || error.message);
      }
      // 网络错误等
      return Promise.reject(error);
    }
  );

  return instance;
};

// 在非单例模式下创建实例，以确保每次请求（尤其是在服务器端）都有正确的baseURL
export const getApiClient = () => createAxiosInstance();

// === 类型定义 ===
export interface AdminUser {
  id: number;
  username: string;
  email: string;
  role: string;
  status: boolean;
  createdAt: string;
  lastLogin: string;
}

export interface Article {
  id: number;
  title: string;
  slug: string;
  content: string;
  summary?: string;
  author: string;
  categoryId: number;
  status: boolean;
  coverImage?: string;
  tags: string[];
  views: number;
  likes: number;
  comments: number;
  isTop: boolean;
  isRecommend: boolean;
  publishedAt?: string;
  createdAt: string;
  updatedAt: string;
  category: {
    id: number;
    name: string;
    description?: string;
  };
  adminUser?: AdminUser | null;
}

export interface Category {
  id: number;
  name: string;
  description?: string;
  sort?: number;
  status?: boolean;
}

export interface ArticleStats {
  total: number;
  published: number;
  draft: number;
  top: number;
  recommend: number;
}

export interface PaginatedArticles {
  articles: Article[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

// 攻略相关类型定义
export interface Case {
  id: number;
  title: string;
  slug: string;
  content: string;
  summary?: string;
  author: string;
  categoryId: number;
  status: boolean;
  coverImage?: string;
  tags: string[];
  views: number;
  likes: number;
  comments: number;
  isTop: boolean;
  isRecommend: boolean;
  publishedAt?: string;
  createdAt: string;
  updatedAt: string;
  category: {
    id: number;
    name: string;
    description?: string;
  };
  adminUser?: AdminUser | null;
}

export interface Product {
  id: number;
  title: string;
  slug: string;
  content: string;
  summary?: string;
  author: string;
  categoryId: number;
  status: boolean;
  coverImage?: string;
  screenshots?: string[]; // 产品截图URL数组
  views: number;
  likes: number;
  comments: number;
  isTop: boolean;
  isRecommend: boolean;
  publishedAt?: string;
  websiteUrl?: string;
  developerAvatar?: string;
  developerNickname?: string;
  developerBio?: string;
  createdAt: string;
  updatedAt: string;
  category: {
    id: number;
    name: string;
    description?: string;
  };
  adminUser?: AdminUser | null;
}

export interface ProductCategory {
  id: number;
  name: string;
  description?: string;
  sort?: number;
  status?: boolean;
}

export interface ProductStats {
  total: number;
  published: number;
  draft: number;
  top: number;
  recommend: number;
}

export interface PaginatedProducts {
  products: Product[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

export interface CaseCategory {
  id: number;
  name: string;
  description?: string;
  sort?: number;
  status?: boolean;
}

export interface CaseStats {
  total: number;
  published: number;
  draft: number;
  top: number;
  recommend: number;
}

export interface PaginatedCases {
  cases: Case[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

export interface ApiResponse<T> {
  success: boolean;
  data: T;
  error?: string;
}

// === 用户端接口 ===
export const webAPI = {
  getArticles: (params?: { page?: number; limit?: number; categoryId?: number; status?: boolean; keyword?: string; isTop?: boolean; isRecommend?: boolean; sort?: string }): Promise<ApiResponse<PaginatedArticles>> => {
    return getApiClient().get(`/api/web/articles`, { params });
  },

  getArticleBySlug: (slug: string): Promise<ApiResponse<Article>> => {
    return getApiClient().get(`/api/web/articles/slug/${slug}`);
  },

  getCategories: (): Promise<ApiResponse<Category[]>> => {
    return getApiClient().get("/api/web/categories");
  },

  getRecommendArticles: (limit?: number): Promise<ApiResponse<Article[]>> => {
    const params = limit ? { limit } : {};
    return getApiClient().get(`/api/web/articles/recommend`, { params });
  },

  getTopArticles: (limit?: number): Promise<ApiResponse<Article[]>> => {
    const params = limit ? { limit } : {};
    return getApiClient().get(`/api/web/articles/top`, { params });
  },

  // 攻略相关接口
  getCases: (params?: { page?: number; limit?: number; categoryId?: number; keyword?: string; sort?: string }): Promise<ApiResponse<PaginatedCases>> => {
    return getApiClient().get(`/api/web/cases`, { params });
  },

  getCaseBySlug: (slug: string): Promise<ApiResponse<Case>> => {
    return getApiClient().get(`/api/web/cases/slug/${slug}`);
  },

  getCaseCategories: (): Promise<ApiResponse<CaseCategory[]>> => {
    return getApiClient().get("/api/web/case-categories");
  },

  getRecommendCases: (limit?: number): Promise<ApiResponse<Case[]>> => {
    const params = limit ? { limit } : {};
    return getApiClient().get(`/api/web/cases/recommend`, { params });
  },

  getTopCases: (limit?: number): Promise<ApiResponse<Case[]>> => {
    const params = limit ? { limit } : {};
    return getApiClient().get(`/api/web/cases/top`, { params });
  },

  // 产品相关接口
  getProducts: (params?: { page?: number; pageSize?: number; categoryId?: number; keyword?: string; sort?: string }): Promise<ApiResponse<PaginatedProducts>> => {
    return getApiClient().get(`/api/web/products`, { params });
  },

  getProductBySlug: (slug: string): Promise<ApiResponse<Product>> => {
    return getApiClient().get(`/api/web/products/${slug}`);
  },

  getProductCategories: (): Promise<ApiResponse<ProductCategory[]>> => {
    return getApiClient().get("/api/web/product-categories");
  },

  getRecommendProducts: (limit?: number): Promise<ApiResponse<Product[]>> => {
    const params = limit ? { limit } : {};
    return getApiClient().get(`/api/web/products/recommend`, { params });
  },

  getTopProducts: (limit?: number): Promise<ApiResponse<Product[]>> => {
    const params = limit ? { limit } : {};
    return getApiClient().get(`/api/web/products/top`, { params });
  },
};

// --- 登录管理 ---
// 定义登录成功后的用户类型
interface LoggedInUser {
  id: number;
  username: string;
  email: string | null;
  roles: string[];
}

// 定义登录接口的完整响应类型
interface LoginResponse {
  success: boolean;
  message?: string;
  error?: string;
  user?: LoggedInUser;
}

// === 后端管理接口 ===
export const adminAPI = {
  // --- 文章管理 ---
  getArticles: (params?: { page?: number; limit?: number; categoryId?: number; status?: boolean; keyword?: string; userId?: number; sort?: string }): Promise<ApiResponse<PaginatedArticles>> => {
    return getApiClient().get(`/api/admin/articles`, { params });
  },

  getArticleById: (id: number): Promise<ApiResponse<Article>> => {
    return getApiClient().get(`/api/admin/articles/${id}`);
  },

  createArticle: (data: Partial<Article>): Promise<ApiResponse<Article>> => {
    return getApiClient().post("/api/admin/articles", data);
  },

  updateArticle: (id: number, data: Partial<Article>): Promise<ApiResponse<Article>> => {
    return getApiClient().put(`/api/admin/articles/${id}`, data);
  },

  deleteArticle: (id: number): Promise<ApiResponse<null>> => {
    return getApiClient().delete(`/api/admin/articles/${id}`);
  },

  getArticleStats: (): Promise<ApiResponse<ArticleStats>> => {
    return getApiClient().get("/api/admin/articles/stats");
  },

  exportArticles: (params?: { categoryId?: number; status?: boolean; keyword?: string; userId?: number; sort?: string }): Promise<Blob> => {
    return getApiClient().get("/api/admin/articles/export", { 
      params,
      responseType: 'blob'
    });
  },

  // --- 分类管理 ---
  getCategories: (): Promise<ApiResponse<Category[]>> => {
    return getApiClient().get("/api/admin/categories");
  },

  getCategoryById: (id: number): Promise<ApiResponse<Category>> => {
    return getApiClient().get(`/api/admin/categories/${id}`);
  },

  createCategory: (data: Partial<Category>): Promise<ApiResponse<Category>> => {
    return getApiClient().post("/api/admin/categories", data);
  },

  updateCategory: (id: number, data: Partial<Category>): Promise<ApiResponse<Category>> => {
    return getApiClient().put(`/api/admin/categories/${id}`, data);
  },

  deleteCategory: (id: number): Promise<ApiResponse<null>> => {
    return getApiClient().delete(`/api/admin/categories/${id}`);
  },

  // --- 攻略管理 ---
  getCases: (params?: { page?: number; limit?: number; categoryId?: number; status?: boolean; keyword?: string; userId?: number; sort?: string }): Promise<ApiResponse<PaginatedCases>> => {
    return getApiClient().get(`/api/admin/cases`, { params });
  },

  getCaseById: (id: number): Promise<ApiResponse<Case>> => {
    return getApiClient().get(`/api/admin/cases/${id}`);
  },

  createCase: (data: Partial<Case>): Promise<ApiResponse<Case>> => {
    return getApiClient().post("/api/admin/cases", data);
  },

  updateCase: (id: number, data: Partial<Case>): Promise<ApiResponse<Case>> => {
    return getApiClient().put(`/api/admin/cases/${id}`, data);
  },

  deleteCase: (id: number): Promise<ApiResponse<null>> => {
    return getApiClient().delete(`/api/admin/cases/${id}`);
  },

  getCaseStats: (): Promise<ApiResponse<CaseStats>> => {
    return getApiClient().get("/api/admin/cases/stats");
  },

  exportCases: (params?: { categoryId?: number; status?: boolean; keyword?: string; userId?: number; sort?: string }): Promise<Blob> => {
    return getApiClient().get("/api/admin/cases/export", { 
      params,
      responseType: 'blob'
    });
  },

  // --- 攻略分类管理 ---
  getCaseCategories: (): Promise<ApiResponse<CaseCategory[]>> => {
    return getApiClient().get("/api/admin/case-categories");
  },

  getCaseCategoryById: (id: number): Promise<ApiResponse<CaseCategory>> => {
    return getApiClient().get(`/api/admin/case-categories/${id}`);
  },

  createCaseCategory: (data: Partial<CaseCategory>): Promise<ApiResponse<CaseCategory>> => {
    return getApiClient().post("/api/admin/case-categories", data);
  },

  updateCaseCategory: (id: number, data: Partial<CaseCategory>): Promise<ApiResponse<CaseCategory>> => {
    return getApiClient().put(`/api/admin/case-categories/${id}`, data);
  },

  deleteCaseCategory: (id: number): Promise<ApiResponse<null>> => {
    return getApiClient().delete(`/api/admin/case-categories/${id}`);
  },

  // --- 产品管理 ---
  getProducts: (params?: { page?: number; pageSize?: number; categoryId?: number; status?: boolean; keyword?: string; userId?: number; sort?: string }): Promise<ApiResponse<PaginatedProducts>> => {
    return getApiClient().get(`/api/admin/products`, { params });
  },

  getProductById: (id: number): Promise<ApiResponse<Product>> => {
    return getApiClient().get(`/api/admin/products/${id}`);
  },

  createProduct: (data: Partial<Product>): Promise<ApiResponse<Product>> => {
    return getApiClient().post("/api/admin/products", data);
  },

  updateProduct: (id: number, data: Partial<Product>): Promise<ApiResponse<Product>> => {
    return getApiClient().put(`/api/admin/products/${id}`, data);
  },

  deleteProduct: (id: number): Promise<ApiResponse<null>> => {
    return getApiClient().delete(`/api/admin/products/${id}`);
  },

  getProductStats: (): Promise<ApiResponse<ProductStats>> => {
    return getApiClient().get("/api/admin/products/stats");
  },

  exportProducts: (params?: { categoryId?: number; status?: boolean; keyword?: string; userId?: number; sort?: string }): Promise<Blob> => {
    return getApiClient().get("/api/admin/products/export", { 
      params,
      responseType: 'blob'
    });
  },

  // --- 产品分类管理 ---
  getProductCategories: (): Promise<ApiResponse<ProductCategory[]>> => {
    return getApiClient().get("/api/admin/product-categories");
  },

  getProductCategoryById: (id: number): Promise<ApiResponse<ProductCategory>> => {
    return getApiClient().get(`/api/admin/product-categories/${id}`);
  },

  createProductCategory: (data: Partial<ProductCategory>): Promise<ApiResponse<ProductCategory>> => {
    return getApiClient().post("/api/admin/product-categories", data);
  },

  updateProductCategory: (id: number, data: Partial<ProductCategory>): Promise<ApiResponse<ProductCategory>> => {
    return getApiClient().put(`/api/admin/product-categories/${id}`, data);
  },

  deleteProductCategory: (id: number): Promise<ApiResponse<null>> => {
    return getApiClient().delete(`/api/admin/product-categories/${id}`);
  },

  // --- 登录管理 ---
  getCaptcha: (): Promise<{ success: boolean; captchaId: string; captchaSvg: string }> => {
    return getApiClient().get("/api/admin/captcha");
  },
  getLoginStatus: (): Promise<{ success: boolean; data: { isLocked: boolean; remainingTime: number; failureCount: number; maxAttempts: number } }> => {
    return getApiClient().get("/api/admin/login-status");
  },
  login: (credentials: { username: string; password: string; captchaId: string; captchaCode: string }): Promise<LoginResponse> => {
    return getApiClient().post("/api/admin/login", credentials);
  },
  logout: (): Promise<{ success: boolean; message: string }> => {
    return getApiClient().post("/api/admin/logout");
  },
};

export interface OssSign {
  accessKeyId: string;
  policy: string;
  signature: string;
  dir: string;
  host: string;
  expire: number;
}
// OSS签名API
export const ossAPI = {
  getSign: (): Promise<ApiResponse<OssSign>> => getApiClient().get("/api/admin/oss/sign"),
};

export const adminUserAPI = {
  getUsers: (): Promise<ApiResponse<AdminUser[]>> => getApiClient().get("/api/admin/users"),
  getUserStats: (): Promise<ApiResponse<{ total: number; active: number; inactive: number }>> => getApiClient().get("/api/admin/users/stats"),
  createUser: (data: Partial<AdminUser> & { password: string }): Promise<ApiResponse<AdminUser>> => getApiClient().post("/api/admin/users", data),
  updateUser: (id: number, data: Partial<AdminUser> & { password?: string }): Promise<ApiResponse<AdminUser>> => getApiClient().put(`/api/admin/users/${id}`, data),
  deleteUser: (id: number): Promise<ApiResponse<null>> => getApiClient().delete(`/api/admin/users/${id}`),
};

// 健康检查
export const healthAPI = {
  check: (): Promise<{ status: string }> => {
    return getApiClient().get("/health");
  },
};
